#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QString path;
    QDir dir;
    path=dir.currentPath();

    ui->setupUi(this);
    this->setGeometry(600,35,560,320);
    this->setFixedSize(282,200);
    this->setWindowTitle(tr("设备状态记录器"));
    ui->SaveLocation->setText(path+"/error.log");

    QString PortName=ui->PortNamecomboBox->currentText();
    myCom=new Win_QextSerialPort(PortName,QextSerialBase::EventDriven);

    Init_Port();

}


void MainWindow::Read_Port()
{

    temp=this->myCom->readAll();
    QString buf;
    buf = temp.toHex();//转换为16进制

//    QDataStream out(&temp,QIODevice::ReadWrite);
//    QString buf;
//    while(!out.atEnd())
//    {
//          qint8 outChar = 0;
//          out>>outChar;
//          QString str = QString("%1").arg(outChar&0xFF,4,16,QLatin1Char('0'));//转换为16进制
//          buf += str;
//    }
////    ui->textBrowser->insertPlainText(buf);
    if (buf != NULL)
        ReadSettings(buf);
}

void MainWindow::ReadSettings(QString buf)
{
    QString path;
    QDir dir;
    path=dir.currentPath();

    QSettings *configIniRead = new QSettings(path+"/config.ini", QSettings::IniFormat);
    if(configIniRead == NULL)
        exit(-1);

    //将读取到的ini文件保存在QString中，先取值，然后通过toString()函数转换成QString类型
    QString ipResult = configIniRead->value("/log/"+buf).toString().toUtf8();// + '\n';
    if ( ipResult.isEmpty() )
        ipResult = tr("Unknown Error").toUtf8();
    QDateTime date_time = QDateTime::currentDateTime();
    QString current_date = date_time.toString("yyyy-MM-dd hh:mm:ss");
    //打印得到的结果
    ipResult = '[' + current_date + ']' + ipResult;
//    qDebug() << ipResult;
    //读入入完成后删除指针
    delete configIniRead;

    path = ui->SaveLocation->text();
    file = new QFile(path);

    if( file->open(QIODevice::WriteOnly | QIODevice::Append) )
    {
//        QTextStream txtOutput(file);
//        txtOutput << ipResult;
        file->write((char *)ipResult.toLatin1().data());
    }

    file->close();

}


MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_Openbtn_clicked()
{
    if(!myCom->isOpen()){

        Init_Port();
        if ( !myCom->open(QIODevice::ReadWrite))
            QMessageBox::critical(this, QObject::tr("错误"),QObject::tr("串口打开失败"));
        else
        {
            ui->Openbtn->setText(tr("关闭串口"));
            ui->BaudRatecomboBox->setEnabled(false);
            ui->DataBitscomboBox_2->setEnabled(false);
            ui->PortNamecomboBox->setEnabled(false);
            ui->ParitycomboBox_3->setEnabled(false);
            ui->StopBitscomboBox_4->setEnabled(false);
        }
    }
    else{

        myCom->close();
        ui->BaudRatecomboBox->setEnabled(true);
        ui->DataBitscomboBox_2->setEnabled(true);
        ui->PortNamecomboBox->setEnabled(true);
        ui->ParitycomboBox_3->setEnabled(true);
        ui->StopBitscomboBox_4->setEnabled(true);
        ui->Openbtn->setText(tr("打开串口"));
    }
}


void MainWindow::Init_Port()
{
    QString PortName=ui->PortNamecomboBox->currentText();
    myCom=new Win_QextSerialPort(PortName,QextSerialBase::EventDriven);

    if(ui->BaudRatecomboBox->currentText()==tr("9600"))
        myCom->setBaudRate(BAUD9600);
    else if(ui->BaudRatecomboBox->currentText()==tr("115200"))
        myCom->setBaudRate(BAUD115200);
    else if(ui->BaudRatecomboBox->currentText()==tr("19200"))
        myCom->setBaudRate(BAUD19200);


    if(ui->DataBitscomboBox_2->currentText()==tr("8"))
        myCom->setDataBits(DATA_8);
    else if(ui->DataBitscomboBox_2->currentText()==tr("7"))
        myCom->setDataBits(DATA_7);
    else
        myCom->setDataBits(DATA_6);

    if(ui->ParitycomboBox_3->currentText()==tr("NONE"))
        myCom->setParity(PAR_NONE);
    else if(ui->ParitycomboBox_3->currentText()==tr("ODD"))
        myCom->setParity(PAR_ODD);
    else
        myCom->setParity(PAR_EVEN);

    if(ui->StopBitscomboBox_4->currentText()==tr("1"))
        myCom->setStopBits(STOP_1);
    else
        myCom->setStopBits(STOP_2);

    myCom->setFlowControl(FLOW_OFF);
    myCom->setTimeout(500);

    connect(myCom,SIGNAL(readyRead()),this,SLOT(Read_Port()));
}


void MainWindow::on_openFile_clicked()
{
    QString filename=QFileDialog::getOpenFileName(this,QString("Open"));

    if(!filename.isEmpty())
    {

        ui->SaveLocation->setText(filename);
    }
}
